package com.conferenceroom.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.conferenceroom.dto.AjaxResult;
import com.conferenceroom.dto.ReservationRequest;
import com.conferenceroom.entity.Orders;
import com.conferenceroom.entity.Room;
import com.conferenceroom.entity.User;
import com.conferenceroom.mapper.OrdersMapper;
import com.conferenceroom.mapper.RoomMapper;
import com.conferenceroom.service.OrdersService;
import com.conferenceroom.service.RoomService;
import com.conferenceroom.service.UserService;
import com.conferenceroom.vo.OrderWithCaltime;
import com.conferenceroom.vo.ReservationOrder;
import com.conferenceroom.vo.refundOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Override
    public List<Orders> list(QueryWrapper<Orders> queryWrapper) {
        return baseMapper.selectList(queryWrapper);
    }

    //根据用户id,返回有倒计时vo的订单
    @Override
    public List<OrderWithCaltime> listWithTime(Integer userId) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<Orders> ordersList = baseMapper.selectList(queryWrapper);
        List<OrderWithCaltime> result = ordersList.stream()
                .map(OrderWithCaltime::build)
                .toList();
        return result;
    }

    @Override
    public OrderWithCaltime getOrderWithCountdownById(Integer orderId) {
        // 1. 查询订单是否存在
        Orders order = baseMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 构建带倒计时的订单视图对象
        return OrderWithCaltime.build(order);
    }

    @Override
    public ReservationOrder createReservation(ReservationRequest request) {
        // 1. 查询用户和会议室信息
        User user = userService.getById(request.getUserId());
        Room room = roomMapper.selectById(request.getRoomId());

        // 2. 定义日期时间格式化器并解析时间
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = formatter.parse(request.getStartTime());
            endTime = formatter.parse(request.getEndTime());
        } catch (ParseException e) {
            throw new RuntimeException("时间格式不正确", e);
        }

        // 3. 计算费用 (使用毫秒计算小时数)
        long hours = (endTime.getTime() - startTime.getTime()) / (1000 * 60 * 60);
        Integer totalFee = (int)(hours * room.getPrice());

        // 3. 构建并插入订单数据
        Orders order = new Orders();
        order.setUserId(Integer.valueOf(request.getUserId()));
        order.setRoomId(Integer.valueOf(request.getRoomId()));
        order.setStartTime(startTime);
        order.setEndTime(endTime);
        order.setCancelTime(null);
        order.setPaymentStatus(0); // 设置为已预约状态
        order.setTotalFee(totalFee);
        order.setRefundFee(0);
        baseMapper.insert(order); // 插入订单

        // 4. 构建 ReservationOrder 对象
        return ReservationOrder.builder()
                .orderId(String.valueOf(order.getOrderId()))
                .roomName(room.getRoomname())
                .startTime(order.getStartTime())
                .endTime(order.getEndTime())
                .username(user.getUsername())
                .realName(user.getRealName())
                .phone(user.getPhone())
                .company(user.getCompany())
                .totalFee(totalFee)
                .build();
    }

    @Override
    public AjaxResult payOrder(Integer orderId) {
        // 1. 查询订单是否存在
        Orders order = baseMapper.selectById(orderId);
        if (order == null) {
            return AjaxResult.fail("订单不存在");
        }

        // 2. 检查订单状态
        if (order.getPaymentStatus() != 0) {
            return AjaxResult.fail("订单状态异常，无法支付");
        }

        // 3. 模拟支付处理
        try {
            // 模拟支付延迟
            Thread.sleep(1000);

            // 更新订单状态为已支付(1)
            order.setPaymentStatus(1);
            baseMapper.updateById(order);

            return AjaxResult.success("支付成功");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return AjaxResult.fail("支付处理异常");
        } catch (Exception e) {
            return AjaxResult.fail("支付失败: " + e.getMessage());
        }
    }

    @Override
    public AjaxResult cancelUnpaidOrder(Integer orderId) {
        // 1. 查询订单是否存在
        Orders order = getById(orderId);
        if (order == null) {
            return AjaxResult.fail("订单不存在");
        }

        // 2. 检查订单状态是否为未支付
        if (order.getPaymentStatus() != 0) {
            return AjaxResult.fail("只有未支付的订单可以取消");
        }


        // 3. 执行取消操作
        order.setPaymentStatus(3); // 3表示已取消
        order.setCancelTime(new Date());
        updateById(order);

        return AjaxResult.success("订单取消成功");
    }

    // OrdersServiceImpl.java
    @Override
    public IPage<Orders> pageByCondition(IPage<Orders> page, Orders order) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        if (order.getOrderId() != null) {
            wrapper.eq("order_id", order.getOrderId());
        }
        if (order.getUserId() != null) {
            wrapper.eq("user_id", order.getUserId());
        }
        if (order.getRoomId() != null) {
            wrapper.eq("room_id", order.getRoomId());
        }
        if (order.getPaymentStatus() != null) {
            wrapper.eq("payment_status", order.getPaymentStatus());
        }

        return baseMapper.selectPage(page, wrapper);
    }



    //定时任务，对于超时的预约订单。不允许支付并且取消
    @Scheduled(fixedRate = 30000) // 每30s执行一次
    public void autoCancelOrders() {
        // 查询所有未支付且倒计时结束的订单
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("payment_status", 0); // 已预约状态

        List<Orders> ordersList = baseMapper.selectList(queryWrapper);

        Date now = new Date();
        for (Orders order : ordersList) {
            Date createTime = order.getCreateTime();

            // 计算时间差（毫秒）
            long diffInMillis = now.getTime() - createTime.getTime();
            long minutes = diffInMillis / (1000 * 60); // 转换为分钟

            if (minutes > 30) { // 倒计时结束（假设倒计时为30分钟）
                // 自动取消订单
                order.setPaymentStatus(3); // 设置为已失效状态
                baseMapper.updateById(order);
            }
        }
    }


    public List<refundOrder> getRefundableOrdersWithRefundFee() {
        List<refundOrder> refundOrders = ordersMapper.selectRefundOrders();

        for (refundOrder order : refundOrders) {
            calculateRefundFee(order);
        }

        return refundOrders;
    }

    public void calculateRefundFee(refundOrder order) {
        Date now = new Date();
        Date startTime = order.getStartTime();

        long diffInMillis = startTime.getTime() - now.getTime();
        long hoursDifference = diffInMillis / (60 * 60 * 1000); // 转换为小时

        if (hoursDifference >= 72) {
            order.setRefundFee(order.getTotalFee()); // 全额退款
        } else if (hoursDifference >= 48) {
            order.setRefundFee((int) (order.getTotalFee() * 0.75)); // 退75%
        } else if (hoursDifference >= 24) {
            order.setRefundFee((int) (order.getTotalFee() * 0.25)); // 退25%
        } else {
            order.setRefundFee(0); // 不满足条件不退款
        }
    }

    @Override
    public boolean updateOrderStatusById(Integer orderId, Integer newStatus) {
        Orders order = ordersMapper.selectById(orderId);
        if (order == null) {
            return false;
        }
        order.setPaymentStatus(newStatus); // paymentStatus 是订单状态字段
        return ordersMapper.updateById(order) > 0;
    }

    @Override
    public Integer updateOrderStatusWithRefund(Integer orderId) {
        Orders order = ordersMapper.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        Integer paymentStatus = order.getPaymentStatus();

        if (paymentStatus == 0) {
            // 状态为 0（未支付）→ 改为 3（订单失效）
            order.setPaymentStatus(3);
            order.setRefundFee(0); // 退款金额为 0
            ordersMapper.updateById(order);
            return 0;
        } else if (paymentStatus == 1) {
            // 状态为 1（已支付）→ 改为 4（退款待审核）

            Date now = new Date();
            Date startTime = order.getStartTime();

            long diffInMillis = startTime.getTime() - now.getTime();
            long hoursDifference = diffInMillis / (60 * 60 * 1000); // 转换为小时

            int refundFee;

            if (hoursDifference >= 72) {
                refundFee = order.getTotalFee(); // 全额退款
            } else if (hoursDifference >= 48) {
                refundFee = (int) (order.getTotalFee() * 0.75); // 退75%
            } else if (hoursDifference >= 24) {
                refundFee = (int) (order.getTotalFee() * 0.25); // 退25%
            } else {
                // 距离开始时间小于24小时 → 不允许退款
                return -1; // 特殊标识表示不可退款
            }

            // 更新状态和退款金额
            order.setPaymentStatus(4); // 设置为退款待审核
            order.setRefundFee(refundFee);
            ordersMapper.updateById(order);

            return refundFee;
        } else {
            throw new RuntimeException("订单状态不允许退款操作");
        }
    }

    @Override
    public IPage<Orders> pageByUserIds(IPage<Orders> page, List<Integer> userIds) {
        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", userIds); // 根据 user_ids 查询
        return baseMapper.selectPage(page, wrapper);
    }



}

